use std::{collections::HashMap, io::Read};

pub fn converter(input: &str) -> String {
    let mut t2s: HashMap<String, String> = HashMap::new();
    let content = read_from_file("t2s.txt");
    let list: Vec<&str> = content.split("\n").filter(|&s| !s.is_empty()).collect();
    list.iter().for_each(|&item| {
        let pos1 = item.find("(").unwrap();
        let pos2 = item.find(")").unwrap();
        let t = &item[..pos1];
        let s = &item[pos1+1..pos2];
        t2s.insert(t.to_string(), s.to_string());
    });
    
    let mut zi_to_pin: HashMap<String, String> = HashMap::new();
    let mut pin_to_wei: HashMap<String, String> = HashMap::new();
    let binding = read_from_file("zi2pin.txt");
    let zi_pin_list: Vec<&str> = binding.split("\n").filter(|&s| !s.is_empty()).collect();
    zi_pin_list.iter().for_each(|&item| {
        let [pin, zi] = item.split(" ").filter(|&s| !s.is_empty()).collect::<Vec<&str>>()[..2] else {panic!("")};
        zi.chars().for_each(|z| {
            zi_to_pin.insert(z.to_string(), pin.to_string());
        });
    });
    let binding = read_from_file("pin2wei.txt");
    let pin_wei_list: Vec<&str> = binding.split("\n").collect();
    pin_wei_list.iter().for_each(|&item| {
        let [wei, pin] = item.split("\t").collect::<Vec<&str>>()[..2] else {panic!("")};
        pin_to_wei.insert(pin.to_string(), wei.to_string());
    });

    let mut ans: String = String::new();
    input.chars().enumerate().for_each(|(i, z)| {
        if let Some(s) = zi_to_pin.get(&z.to_string()) {
            if i != 0 {
                ans += " ";
            }
            ans += pin_to_wei.get(s).unwrap();
        } else if let Some(s0) = t2s.get(&z.to_string()) {
            if i != 0 {
                ans += " ";
            }
            ans += pin_to_wei.get(zi_to_pin.get(s0).unwrap()).unwrap();
        }
    });
    
    if !ans.is_empty() {
        ans.replace_range(0..1, &ans[..1].to_uppercase()) ;
    }
    
    ans
}

fn read_from_file(filename: &str) -> String {
    let mut file = match std::fs::File::open(filename) {
        Err(e) => panic!("无法打开文件: {}", e),
        Ok(f) => f,
    };
    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Err(e) => panic!("读取文件出错: {}", e),
        Ok(_) => (),
    }
    contents
}
